package org.example.controller;

import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * java使用es7.x api 操作索引、文档
 */
@Slf4j
@RestController
@RequestMapping("/api/example")
public class JavaEs7Controller {

    static RestHighLevelClient client;

    public static RestHighLevelClient getClient() {
        if (client == null) {
            RestClientBuilder build = RestClient.builder(HttpHost.create("http://192.168.101.104:9200"))
                    .setHttpClientConfigCallback(httpAsyncClientBuilder -> {
                        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "123456"));
                        return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    });
            client = new RestHighLevelClient(build);
        }
        return client;
    }

    @PostMapping("/createIndex")
    public void createIndex(String indexName) throws IOException {
        // 设置索引
        CreateIndexRequest indexRequest = new CreateIndexRequest(indexName);
        // 配置索引设置
        indexRequest.settings(Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 2));

        // 执行创建索引请求
        CreateIndexResponse response = getClient().indices()
                .create(indexRequest, RequestOptions.DEFAULT);

        boolean acknowledged = response.isAcknowledged();
        if (acknowledged) {
            log.info("索引创建成功");
        } else {
            log.info("创建失败");
        }
    }

    @DeleteMapping("/deleteIndex")
    public boolean deleteIndex(String indexName) throws IOException {
        RestHighLevelClient client = getClient();
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        return response.isAcknowledged();
    }

    @PostMapping("/addDoc")
    public String addDoc(String indexName, String id,  String json) throws IOException {
        RestHighLevelClient client = getClient();

        IndexRequest request = new IndexRequest(indexName);
        if (id != null && !id.isEmpty()) {
            request.id(id);
        }
        request.source(json, XContentType.JSON);

        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        return response.getId();
    }

    @GetMapping("/queryDoc")
    public String queryDoc(String indexName, String context) throws IOException {
        RestHighLevelClient client = getClient();
        GetRequest request = new GetRequest(indexName,"2");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);


        if (response.isExists()) {
            System.out.println(response.getSourceAsString());
            return response.getSourceAsString();
        } else {
            return null;
        }
    }

    @PutMapping("/updateDoc")
    public boolean updateDoc(String indexName, String id, String json) throws IOException {
        RestHighLevelClient client = getClient();
        UpdateRequest request = new UpdateRequest(indexName, id);
        request.doc(json, XContentType.JSON);

        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        return response.getResult().equals(UpdateResponse.Result.UPDATED);
    }

    @DeleteMapping("/delDoc")
    public boolean delDoc(String indexName, String id) throws IOException {
        RestHighLevelClient client = getClient();
        DeleteRequest request = new DeleteRequest(indexName, id);
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);

        return response.getResult() == DeleteResponse.Result.DELETED;
    }


}